const fs = require("fs");
const path = require("path");
const { getBlockSchema, getDefaultBlock, themeList } = require("../tool/util");
const configPath = "../../default_config_zhCN"
const sectionPath = "../../default_zhCN"
const { zhCN, enUS } = require(configPath);

function findZhCn(data) {
    const result = [];
    if (typeof data === "object") {
        for (const key in data) {
            if (key === "zh_CN") {
                if (data[key] && !findZhCNStr(data[key])) {
                    result.push(data[key]);
                }
            } else {
                result.push(...findZhCn(data[key]));
            }
        }
    }

    return result;
}

function findEnUsStr(val) {
    for (let i = 0; i < zhCN.length; i++) {
        const element = zhCN[i];
        for (let x = 0; x < element.length; x++) {
            const zh_CN = element[x];
            if (zh_CN == val) {
                return enUS[i][x].trim();
            }
        }
    }
}

function findZhCNStr(val) {
    for (let i = 0; i < zhCN.length; i++) {
        const element = zhCN[i];
        for (let x = 0; x < element.length; x++) {
            const zh_CN = element[x];
            if (zh_CN == val) {
                return enUS[i][x].trim();
            }
        }
    }
    return "";
}

function findZhCnToEnUs(data) {
    if (typeof data === "object") {
        for (const key in data) {
            if (key === "zh_CN") {
                if (data[key]) {
                    data["en_US"] = findEnUsStr(data[key]);
                }
            } else {
                data[key] = findZhCnToEnUs(data[key]);
            }
        }
    }
    return data;
}

function writeFile(targetFile, content) {
    const dir = path.dirname(targetFile);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
    }
    fs.writeFileSync(targetFile, content);
}

function sliceArr(arr) {
    const length = arr.length;
    const size = Math.ceil(length / 10);
    const result = [];
    for (let i = 0; i < length; i += size) {
        const chunk = arr.slice(i, i + size);
        result.push(chunk);
    }
    return result;
}

function getSectionsLanguage(themes) {
    let zhCN = [];
    themes.forEach((theme) => {
        const src = `./src/theme/${theme}/sections`;
        if (fs.existsSync(src)) {
            const filenames = fs.readdirSync(src);
            filenames.forEach(function (file) {
                const schemJson = getBlockSchema(src + "/" + file);

                if (schemJson) {
                    zhCN = [...zhCN, ...findZhCn(schemJson)];
                }
            });
        }
    });
    const result = sliceArr([...new Set(zhCN)]);
    writeFile("./default_zhCN.js", `var zhCN = ${JSON.stringify(result, "", "\t")};`);
}

function getConfigLanguage(themes) {
    let zhCN = [];
    themes.forEach((theme) => {
        const configSrc = `./src/theme/${theme}/config`;
        if (fs.existsSync(configSrc)) {
            const filenames = fs.readdirSync(configSrc);
            filenames.forEach(function (file) {
                const config = JSON.parse(fs.readFileSync(configSrc + "/" + file, "utf-8"));
                if (config) {
                    zhCN = [...zhCN, ...findZhCn(config)];
                }
            });
        }

        const libConfigSrc = `./src/theme/${theme}/lib/config`;
        if (fs.existsSync(libConfigSrc)) {
            const filenames = fs.readdirSync(libConfigSrc);
            filenames.forEach(function (file) {
                const config = JSON.parse(fs.readFileSync(libConfigSrc + "/" + file, "utf-8"));
                if (config) {
                    zhCN = [...zhCN, ...findZhCn(config)];
                }
            });
        }
    });
    const result = sliceArr([...new Set(zhCN)]);
    writeFile("./default_config_zhCN.js", `var zhCN = ${JSON.stringify(result, "", "\t")};`);
}

function sectionsReplaceSchema(src, body) {
    const content = fs.readFileSync(src, "utf-8");
    const schemaRegExpStr = /{% schema %}([\s\S]*?){% endschema %}/g;
    const newBody = content.replace(schemaRegExpStr, function(){
        return "{% schema %}\n" + body + "\n{% endschema %}"
    });
    writeFile(src, newBody);
}

function setSectionsLanguageUS(themes) {
    themes.forEach((theme) => {
        const src = `./src/theme/${theme}/sections`;
        if (fs.existsSync(src)) {
            const filenames = fs.readdirSync(src);
            filenames.forEach(function (file) {
                const fileSrc = src + "/" + file;
                const schemJson = getBlockSchema(fileSrc);
                const data = findZhCnToEnUs(schemJson);
                sectionsReplaceSchema(fileSrc, JSON.stringify(data, "", "\t"));
            });
        }
    });
}

function setConfigLanguageUS(themes) {
    themes.forEach((theme) => {
        const configSrc = `./src/theme/${theme}/config`;
        if (fs.existsSync(configSrc)) {
            const filenames = fs.readdirSync(configSrc);
            filenames.forEach(function (file) {
                const config = JSON.parse(fs.readFileSync(configSrc + "/" + file, "utf-8"));
                if (config) {
                    const data = findZhCnToEnUs(config);
                    writeFile(configSrc + "/" + file, JSON.stringify(data, "", "\t"));
                }
            });
        }

        const libConfigSrc = `./src/theme/${theme}/lib/config`;
        if (fs.existsSync(libConfigSrc)) {
            const filenames = fs.readdirSync(libConfigSrc);
            filenames.forEach(function (file) {
                const config = JSON.parse(fs.readFileSync(libConfigSrc + "/" + file, "utf-8"));
                if (config) {
                    const data = findZhCnToEnUs(config);
                    writeFile(libConfigSrc + "/" + file, JSON.stringify(data, "", "\t"));
                }
            });
        }
    });
}

function setFirstBig() {
    //去除前后空格、首字母大写
    const result = enUS.map((el)=>{
        return el.map((lang)=>{
            let trimmedStr = lang.trim();
            return trimmedStr.charAt(0).toUpperCase() + trimmedStr.slice(1);
        })
    })
    writeFile("./default_config_zhCN.js", `
    var zhCN = ${JSON.stringify(zhCN,"","\t")};

    var enUS = ${JSON.stringify(result,"", "\t")};
    module.exports = { zhCN, enUS };
    `);
}

function main() {
    // const themes = themeList();

    // 设置多语言
    // setSectionsLanguageUS(['avatar20']);
    // setConfigLanguageUS(['default']);

    // themes.forEach((theme) => {
    //     console.log(theme);
    // });
    

    // function flattenArray(arr) {
    //     return arr.reduce((flat, next) => flat.concat(next), []);
    // }
    // let arr = flattenArray(enUS);
    // const uniqueArr = [...new Set(arr)];
    // writeFile("./default_enUS.js", `var enUS = ${JSON.stringify(uniqueArr,"", "\t")};`);

    // const duplicates = arr.reduce((prev, cur) => {
    //     if (arr.indexOf(cur) !== arr.lastIndexOf(cur) && !prev.includes(cur)) {
    //         prev.push(cur);
    //     }
    //     return prev;
    // }, []);

    // let enUSL = []
    // enUS.forEach((el)=>{
    //     enUSL.push(el.length)
    // })

    // let zhCNl = []
    // zhCN.forEach((el)=>{
    //     zhCNl.push(el.length)
    // })

    // console.log(enUSL,zhCNl);

    //首字母大写
    // setFirstBig()

    // getSectionsLanguage(['ceborn20']);
    // getConfigLanguage(['ceborn20']);

    // setSectionsLanguageUS(['ceborn20'])

    // setConfigLanguageUS(['ceborn20'])
}

main();
